import random
import math
import time
import KBEngine
import KBEDebug as log
import Config as cfg


CODE_SELL_CHICKEN_NOT_FOUND = 10000
CODE_SELL_EGG_NOT_FOUND = 10001

FARM_WIDTH = 8 - 1
FARM_HEIGHT = 4 - 0.5


class AvatarFarm(KBEngine.EntityComponent):

    def __init__(self):
        KBEngine.EntityComponent.__init__(self)

    def onAvatarEnabled(self):
        # 默认给玩家一只鸡
        if self.initChick == 0:
            self.addChicken(10001)
            self.updateChickenPic(10001, 1)
            self.initChick = 1
        if self.lastInGameTime != 0:
            self.offlineIncome()
        self.pushChickens()
        self.pushEggs()
        self.pushChickenPics()

    def rewardChicken(self, gamemode):
        tb_farm_params = cfg.tb_farm.dic[self.farmLevel]
        if len(self.chickens) >= tb_farm_params['maxCount']:  # 农场到达养殖上限
            log.INFO_MSG(f'AvatarFarm.rewardChicken[{self.owner.playerId}] farmLevel:{self.farmLevel} max chicken count')
            return
        self.totalChickenCount += 1
        if gamemode == 1:
            quality = 0
        else:
            quality_lst = cfg.tb_chicken_quality.lst
            rd = random.random()
            total_rd = 0
            end_weight = 0
            idx = 0
            for i in range(1, 5):
                item = quality_lst[i]
                total_rd += item['weight'] * rd
                if total_rd >= end_weight:
                    idx += 1
                    end_weight += quality_lst[idx]['weight']

            rd_item = quality_lst[idx]
            quality = rd_item['quality']
            # 紫色保底
            if quality == 3:
                self.chickenCount1 = 0  # 重置保底
            else:
                self.chickenCount1 += 1
                if self.chickenCount1 >= 10:  # 启用保底
                    quality = 3
                    self.chickenCount1 -= 10
                    log.INFO_MSG(f'AvatarFarm.rewardChicken[{self.owner.playerId}] quality 4')
            # 橙色保底
            if quality == 4:
                self.chickenCount2 = 0
            else:
                self.chickenCount2 += 1
                if self.chickenCount2 >= 50:
                    quality = 4
                    self.chickenCount2 -= 50
                    log.INFO_MSG(f'AvatarFarm.rewardChicken[{self.owner.playerId}] quality 5')

        tb_chicken_params = cfg.quality_2_chickens[quality][0]
        self.addChicken(tb_chicken_params['id'])
        self.client.onAddChicken(self.chickens[-1])
        self.updateChickenPic(tb_chicken_params['id'], 1)

    def AddChickenGM(self, quality):
        tb_chicken_params = cfg.quality_2_chickens[quality][0]
        self.addChicken(tb_chicken_params['id'])
        self.client.onAddChicken(self.chickens[-1])
        self.updateChickenPic(tb_chicken_params['id'], 1)
        self.totalChickenCount += 1

    def updateChickenPic(self, tableId, val):
        for e in self.chickenPics:
            if e['chickenTableId'] == tableId:
                return
        self.chickenPics.append({
            'chickenTableId': tableId,
        })
        self.chickenPics = self.chickenPics
        self.client.onUpdateChickenPic(self.chickenPics[-1])

    def sellChicken(self, uuid):
        for chicken in self.chickens:
            if chicken['uuid'] == uuid:
                self.chickens.remove(chicken)
                self.chickens = self.chickens
                # 根据品质获取该鸡的价值
                quality = cfg.tb_chicken.dic[chicken['tableId']]['quality']
                gold = cfg.tb_chicken_quality.dic[quality]['eggPrice'] * 5
                self.owner.avatarOther.coin += gold
                self.client.onSellChickenSuccess(uuid)
                return
        # 没有找到
        self.client.onResponseMsgCode(CODE_SELL_CHICKEN_NOT_FOUND)

    def sellEgg(self, uuid):
        for egg in self.eggs:
            if egg['uuid'] == uuid:
                self.eggs.remove(egg)
                self.eggs = self.eggs
                quality = cfg.tb_chicken.dic[egg['chickenTableId']]['quality']
                gold = cfg.tb_chicken_quality.dic[quality]['eggPrice']
                self.owner.avatarOther.coin += gold
                self.client.onSellEggSuccess(uuid)
                return
        self.client.onResponseMsgCode(CODE_SELL_EGG_NOT_FOUND)

    def upgradeFarmLevel(self):
        # 判断升级条件
        if self.farmLevel == 15:
            self.client.onUpgradeFarm(2)
            return
        cost = cfg.tb_farm.dic[self.farmLevel]['coinCount']
        if self.owner.avatarOther.coin >= cost:
            self.owner.avatarOther.coin -= cost
            self.farmLevel += 1
            log.DEBUG_MSG(f'player {self.owner.playerId} Upgrade Farm {self.farmLevel}')
            self.client.onUpgradeFarm(0)
        else:
            self.client.onUpgradeFarm(1)

    def dailyRefresh(self):
        # 已经生过蛋的鸡不再继续生蛋，除非那个蛋被卖掉
        spawned_egg_chicken = {}
        for egg in self.eggs:
            spawned_egg_chicken[egg['chickenUUID']] = True
        for chicken in self.chickens:
            if chicken['uuid'] not in spawned_egg_chicken:
                egg = self.createEgg(chicken['uuid'], chicken['tableId'])
                self.eggs.append(egg)
                self.client.onSpawnEgg(egg)
        self.eggs = self.eggs

    def pushChickens(self):
        total_count = len(self.chickens)
        slice_num = 10
        slice_count = math.ceil(total_count / slice_num)
        for i in range(slice_count):
            start = i * slice_num
            end = start + slice_num
            self.client.onPushChickens(self.chickens[start:end], i, total_count)

    def pushChickenPics(self):
        total_count = len(self.chickenPics)
        slice_num = 10
        slice_count = math.ceil(total_count / slice_num)
        for i in range(slice_count):
            start = i * slice_num
            end = start + slice_num
            self.client.onPushChickenPics(self.chickenPics[start:end], i, total_count)

    def pushEggs(self):
        total_count = len(self.eggs)
        slice_num = 40
        slice_count = math.ceil(total_count / slice_num)
        for i in range(slice_count):
            start = i * slice_num
            end = start + slice_num
            self.client.onPushEggs(self.eggs[start:end], i, total_count)

    def addChicken(self, tableId):
        chicken = {
            'uuid': KBEngine.genUUID64(),
            'tableId': tableId
        }
        self.chickens.append(chicken)
        self.chickens = self.chickens

    def createEgg(self, chickenUUID, chickenTableId):
        rd_x = (random.random() - 0.5) * (FARM_WIDTH - 2)
        rd_y = (random.random() - 0.5) * FARM_HEIGHT
        egg = {
            'uuid': KBEngine.genUUID64(),
            'chickenUUID': chickenUUID,
            'chickenTableId': chickenTableId,
            'x': rd_x,
            'y': rd_y
        }
        return egg

    def createEggs(self, offlineDuration):
        # egg_num = int(offlineDuration / 600)
        egg_num = int(offlineDuration / 900)
        if egg_num > 90:
            egg_num = 90
        for i in range(0, egg_num):
            for chicken in self.chickens:
                egg = self.createEgg(chicken['uuid'], chicken['tableId'])
                self.eggs.append(egg)
        self.eggs = self.eggs

    def createEggsOnLine(self):
        for chicken in self.chickens:
            egg = self.createEgg(chicken['uuid'], chicken['tableId'])
            self.eggs.append(egg)
        self.eggs = self.eggs

    def layEgg(self, chickenUUID, chickenTableId, x, y):
        egg = {
            'uuid': KBEngine.genUUID64(),
            'chickenUUID': chickenUUID,
            'chickenTableId': chickenTableId,
            'x': x,
            'y': y
        }
        self.eggs.append(egg)
        self.client.onSpawnEgg(egg)
        self.eggs = self.eggs

    def sellEggs(self):
        golds = 0
        for egg in self.eggs:
            #     # self.eggs.remove(egg)
            #     # self.eggs = self.eggs
            quality = cfg.tb_chicken.dic[egg['chickenTableId']]['quality']
            gold = cfg.tb_chicken_quality.dic[quality]['eggPrice']
            golds += gold
        self.client.onSellEggsSuccess()
        self.owner.avatarOther.coin += golds
        self.eggs = []

    def offlineIncome(self):
        if self.lastIsOffline != 1:
            return
        self.lastIsOffline = 0
        per_coin = 0
        for chicken in self.chickens:
            quality = cfg.tb_chicken.dic[chicken['tableId']]['quality']
            gold = cfg.tb_chicken_quality.dic[quality]['eggPrice']
            per_coin += gold
        log.DEBUG_MSG(f'per income {per_coin}')
        offtime = int(time.time()) - self.lastInGameTime
        # count = offtime // 600
        count = offtime // 900 # 变为原来的2/3
        coin_count = per_coin * count
        log.DEBUG_MSG(f'离线收益:{coin_count} {offtime}')
        self.client.onOfflineIncome(coin_count, count)

    def ReceiveReward(self, coinNum):
        self.owner.avatarOther.coin += coinNum
